package com.orange.quickback.system.service.oss.module.impl;

import com.orange.quickback.system.api.common.result.QBootResult;
import com.orange.quickback.system.dao.oss.module.QBootOssFileInfoRepository;
import com.orange.quickback.system.entities.oss.module.QBootOssFileInfo;
import com.orange.quickback.system.service.oss.module.QBootOssService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class QBootOssServiceImpl implements QBootOssService {
    @Value("${q-boot.q-boot-oss.base-dir}")
    private String qBootOssBaseDir;

    @Value("${q-boot.q-boot-oss.oss-server}")
    private String qBootOssServer;

    @Resource
    QBootOssFileInfoRepository qBootOssFileInfoRepository;
    @Override
    public QBootResult upload(HttpServletRequest req, MultipartFile[] uploadFiles, Principal pl){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String realPath = qBootOssBaseDir + "admin/uploadFile/";
        String format = sdf.format(new Date());
        File folder = new File(realPath + format);
        if(!folder.isDirectory()){
            folder.mkdirs();
        }
        List<String> list = new ArrayList<>();
        try {
            for(MultipartFile uploadFile:uploadFiles) {

                String oldName = uploadFile.getOriginalFilename();
                String newName =
                        UUID.randomUUID().toString() +
                                oldName.substring(oldName.lastIndexOf("."), oldName.length());

                uploadFile.transferTo(new File(folder, newName));
                String filepath = qBootOssServer + "admin/uploadFile/" + format + "/" + newName;
                qBootOssFileInfoRepository.save(new QBootOssFileInfo(oldName,filepath,pl.getName(),uploadFile.getSize()));
                list.add(filepath);
            }
            return QBootResult.build(list);
        }
        catch (IOException e) {
            return QBootResult.buildFail(e.getMessage());
        }

    }

    @Override
    public QBootResult getAllOssFileByPage(int page, int size) {
        PageRequest pageRequest = PageRequest.of(page,size);
        return QBootResult.build(qBootOssFileInfoRepository.findAll(pageRequest));
    }
}
